<?php


namespace common\service;


use common\exception\LogicException;
use common\model\AttributeValueModel;
use common\model\OptionsModel;
use common\model\ProjectMemberModel;
use common\model\ProjectModel;
use common\model\ProjectTemplateModel;
use common\model\UserModel;
use support\ErrorCode;
use support\SingletonTrait;

class ProjectTeamService
{
    use SingletonTrait;

    /**
     * 获取--团队列表
     * @param int $teamId 团队ID
     * @param int $stepCategoryId 环节ID
     * @return array
     */
    public function getTeamConfig(int $teamId = 0, int $stepCategoryId = 0)
    {
        //查询现有配制
        $orgInfo = model(OptionsModel::class)->where(['name' => OptionsModel::NAME_TEAM_CONFIG])->find();
        $configList = json_decode($orgInfo['config'], true);
        if (empty($configList)) {
            $configList = [];
        }

        //过滤---配制
        $list = [];
        $i = 0;
        foreach ($configList as $val) {
            //过滤 已删除
            if ($val['status'] != 1) {
                continue;
            }
            //通过团队ID--指定团队信息
            if ($teamId && $val['id'] != $teamId) {
                continue;
            }
            //通过环节ID--团队信息
            if ($stepCategoryId && !in_array($stepCategoryId, $val['step_category_id'])) {
                continue;
            }
            $list[$i] = $val;
            $i++;
        }

        //排序
        $orderList = array_column($list, 'sort');
        array_multisort($orderList, SORT_ASC, $list);

        $result = [];
        $result['id'] = $orgInfo['id'];
        $result['list'] = $list;
        return $result;
    }


    /**
     * 后台配置—保存团队配制
     * @param array $data
     * @return int
     */
    public function saveTeamConfig(array $data)
    {
        //获取现有配制
        $teamInfo = $this->getTeamConfig();
        //判断参数
        $this->checkTeamConfig($teamInfo['list'], $data);
        //修改配制
        return $this->saveConfigData($teamInfo['id'], $teamInfo['list'], $data);
    }

    /**
     * 检查团队配制---参数
     * @param array $configList 配制
     * @param array $data 传参
     * @return int
     */
    private function checkTeamConfig(array $configList, array $data)
    {
        $id = $data['id'] ?? 0;
        //判断角色是否存在
        $roleList = teamones_request('teamones-im', 'role/select', [])['data']['rows'];
        $allRoleId = array_column($roleList, 'id');
        // 默认角色
        $roleIds = explode(',', $data['role_id']);
        if (array_diff($roleIds, $allRoleId)) {
            throw new LogicException("The default role does not exist", ErrorCode::TEAM_DEFAULT_ROLE_ERROR);
        }

        if ($data['extra_role_id']) {
            $extraRoleIds = explode(',', $data['extra_role_id']);
            if (array_diff($extraRoleIds, $allRoleId)) {
                throw new LogicException("The additional role does not exist", ErrorCode::TEAM_EXTRA_ROLE_ERROR);
            }
        }

        //判断名称是否重复
        if (empty($configList)) {
            return 1;
        }
        $configList = array_filter($configList, function ($tmp) {
            return $tmp['status'] = 1;
        });
        foreach ($configList as $val) {
            if ($val['name'] == $data['name'] && $val['id'] != $id) {
                throw new LogicException("Duplicate group name", ErrorCode::TEAM_NAME_REPEAT);
            }
            //判断环节名是否重复
            if (isset($data['step_category_name']) && isset($val['step_category_name'])) {
                if ($val['step_category_name'] == $data['step_category_name'] && $val['id'] != $id) {
                    throw new LogicException("Duplicate category name", ErrorCode::TEAM_CATEGORY_NAME_REPEAT);
                }
            }
            //判断环节ID--是否重复
            if ($val['id'] != $id && in_array($data['step_category_id'], $val['step_category_id'])) {
                throw new LogicException("Duplicate category", ErrorCode::TEAM_CATEGORY_REPEAT);
            }
        }
        return 1;
    }


    /**
     * 保存配制
     * @param int $id Id
     * @param array $configList 配制
     * @param array $data 传参
     * @return int
     */
    private function saveConfigData(int $id, array $configList, array $data)
    {
        $modifyData = [];
        $modifyData['id'] = $id;
        $modifyData['config'] = $this->getNewConfigList($configList, $data);

        try {
            model(OptionsModel::class)->modifyItem($modifyData);
        } catch (\Exception $e) {
            trace('更新团队配制失败' . PHP_EOL . format_exception_info($e), 'ERR');
        }
        return $data['id'];
    }

    /**
     * 获取修改后的--配制列表
     * @param array $configList 配制列表
     * @param array $data 新增或修改数组
     * @return array
     */
    private function getNewConfigList(array $configList, array &$data)
    {
        //修改还是新增配制
        $configId = $data['id'] ?? 0;
        //新增记录
        if (empty($configId)) {
            //取现在配制最大的id
            $idList = array_column($configList, 'id');
            $data['id'] = 1;
            if ($idList) {
                $data['id'] = max($idList) + 1;
            }
            $configList[] = $data;
        } else {
            //修改指定项
            foreach ($configList as &$val) {
                if ($val['id'] == $configId) {
                    $val = $data;
                }
            }
        }
        return $configList;
    }

    /**
     * 后台配置—删除配制
     * @param string $configIds 配制IDs
     * @return int
     */
    public function delTeamConfig(string $configIds)
    {
        //获取现有配制
        $teamInfo = $this->getTeamConfig();
        //判断
        $configIds = explode(',', $configIds);
        //判断团队是否被使用
        $has = model(ProjectMemberModel::class)->where(['team_id' => ['in', $configIds], 'is_delete' => 0])->field('id')->find();
        if ($has) {
            throw new LogicException("This group is currently in use and cannot be deleted", ErrorCode::TEAM_USE_NOT_DEL);
        }

        //判断团队是否有---岗位配制
        $capacityList = teamones_request('teamones-im', 'capacity/get_capacity_list', [])['data'];
        $teamIds = array_unique(array_column($capacityList, 'team_category_id'));
        foreach ($configIds as $val) {
            if (in_array($val, $teamIds)) {
                throw new LogicException("This team has production capacity allocation and cannot be deleted", ErrorCode::TEAM_USE_CAPACITY_NOT_DEL);
            }
        }

        //删除配制
        $this->batchDelConfig($teamInfo['id'], $teamInfo['list'], $configIds);

        return 1;
    }

    /**
     * 批量删除配制
     * @param int $id 删除配制option表 Id
     * @param array $configList 配制
     * @param array $configIds 配制列表IDs
     * @return int
     */
    private function batchDelConfig(int $id, array $configList, array $configIds)
    {
        //新增记录
        if (empty($configIds)) {
            return 0;
        }
        //修改指定项
        foreach ($configList as &$val) {
            if (in_array($val['id'], $configIds)) {
                $val['status'] = 2;
            }
        }
        $modifyData = [];
        $modifyData['id'] = $id;
        $modifyData['config'] = $configList;

        try {
            model(OptionsModel::class)->modifyItem($modifyData);
        } catch (\Exception $e) {
            trace('删除配制失败' . PHP_EOL . format_exception_info($e), 'ERR');
        }
        return 1;
    }


    /**
     * 获取团队配制列表
     * @param int $projectId 项目ID
     * @param int $templateId 模板ID
     * @param int $teamId 组ID
     * @param int $stepCategoryId 环节ID
     * @return array
     */
    public function getTeamConfigList(int $projectId, int $templateId, int $teamId = 0, int $stepCategoryId = 0)
    {
        //获取现有配制
        $teamInfo = $this->getTeamConfig($teamId, $stepCategoryId);
        //增加--自定义配制
        $configList = $this->filterTeamConfigList($teamInfo['list'], $projectId, $templateId);
        //整理数组
        return $this->clearConfigList($configList);
    }

    /**
     * 整理团队配制--数组
     * @param array $configList 配制列表
     * @return array
     */
    private function clearConfigList(array $configList)
    {
        if (empty($configList)) {
            return [];
        }
        //排序
        $orderList = array_column($configList, 'sort');
        array_multisort($orderList, SORT_ASC, $configList);
        //补充角色名
        $roleList = teamones_request('teamones-im', 'role/select', [])['data']['rows'];
        $roleList = array_column($roleList, null, 'id');

        //环节--详情
        $stepCategoryList = TemplateService::getInstance()->findStepCategoryShowList();
        $stepCategoryList = array_column($stepCategoryList, null, 'id');

        foreach ($configList as &$val) {
            $val['role_list'] = $this->clearRoleList($val['role_id'], $roleList);

            $val['extra_role_list'] = [];
            if (isset($val['extra_role_id'])) {
                $val['extra_role_list'] = $this->clearRoleList($val['extra_role_id'], $roleList);
            }
            //环节详情
            $stepCategory = [];
            foreach ($val['step_category_id'] as $id) {
                if (isset($stepCategoryList[$id])) {
                    $stepCategory[] = $stepCategoryList[$id];
                }
            }
            $val['step_category_list'] = $stepCategory;
        }
        return $configList;
    }

    /**
     * 整理角色信息-列表
     * @param string $roleIds 角色ID
     * @param array $roleList 角色列表
     * @return array
     */
    private function clearRoleList(string $roleIds, array $roleList)
    {
        //角色--信息
        $roleIdList = explode(',', $roleIds);
        $result = [];
        foreach ($roleIdList as $val) {
            if (isset($roleList[$val])) {
                unset($roleList[$val]['created']);
                unset($roleList[$val]['created_by']);
                $result[] = $roleList[$val];
            }
        }
        return $result;
    }


    /**
     * 团队列表--过滤模板定义配制
     * @param array $configList 团队配制列表
     * @param int $projectId 项目ID
     * @param int $templateId 模板ID
     * @return array
     */
    private function filterTeamConfigList(array $configList, int $projectId, int $templateId = 0)
    {
        if (empty($configList)) {
            return [];
        }
        //隐藏--是否需要显示
        $showHide = true;
        //项目ID---查询用于前端
        if ($projectId) {
            $templateId = model(ProjectModel::class)->where(['id' => $projectId])->value('project_template_id');
            if (empty($templateId)) {
                return $configList;
            }
            $showHide = false;
        }
        //无模板--无自定义配制
        if (empty($templateId)) {
            return $configList;
        }

        //查询项目模板
        $tempInfo = model(ProjectTemplateModel::class)->where(["id" => $templateId])->find();
        if (empty($tempInfo['team_config'])) {
            return $configList;
        }

        $teamConfig = json_decode($tempInfo['team_config'], true);
        $hideList = $teamConfig['hide_list'] ?? [];
        //增加自定义团队配制
        if ($showHide) {
            foreach ($configList as &$val) {
                if (in_array($val['id'], $hideList)) {
                    $val['is_show'] = 0;
                } else {
                    $val['is_show'] = 1;
                }
            }
        } else {
            $configList = array_filter($configList, function ($tmp) use ($hideList) {
                return !in_array($tmp['id'], $hideList);
            });
        }

        return $configList;
    }

    /**
     * 后台配置—模板团队--显示隐藏
     * @param int $configId 配制ID
     * @param int $templateId 模板ID
     * @param int $type 操作类型
     * @return int
     */
    public function saveTemplateTeamConfig(int $configId, int $templateId, int $type)
    {
        $projectTemplateModel = model(ProjectTemplateModel::class);
        //查询项目模板
        $tempInfo = $projectTemplateModel->where(["id" => $templateId])->find();
        if (empty($tempInfo)) {
            throw new LogicException("Template does not exist", ErrorCode::TEMPLATE_NOT_EXIST);
        }
        $teamConfig = json_decode($tempInfo['team_config'], true);
        $hideList = $teamConfig['hide_list'] ?? [];

        //显示--操作
        if ($type == 1) {
            if (!in_array($configId, $hideList)) {
                throw new LogicException("It is already showing status", ErrorCode::TEAM_ALREADY_SHOW);
            }
            $hideList = array_values(array_diff($hideList, [$configId]));
        }
        //隐藏--操作
        if ($type == 2) {
            if (in_array($configId, $hideList)) {
                throw new LogicException("It is already hidden", ErrorCode::TEAM_ALREADY_HIDDEN);
            }
            $hideList[] = $configId;
        }
        //判断团队ID是否存在
        $teamInfo = $this->getTeamConfig();
        if (!in_array($configId, array_column($teamInfo['list'], 'id'))) {
            throw new LogicException("Team configuration does not exist", ErrorCode::TEAM_CONFIG_NOT_EXIST);
        }

        //保存隐藏--配制
        $teamConfig['hide_list'] = $hideList;
        $data = [];
        $data['id'] = $tempInfo['id'];
        $data['team_config'] = json_encode($teamConfig);
        $projectTemplateModel->save($data);

        return $configId;
    }

    /**
     * 团队--增加成员
     * @param int $projectId 项目ID
     * @param int $teamId 团队ID
     * @param string $userId 用户ID
     * @return int
     */
    public function teamAddUser(int $projectId, int $teamId, string $userId)
    {
        //获取团队信息
        $teamInfo = $this->getTeamConfig($teamId);
        if (empty($teamInfo['list'])) {
            throw new LogicException("Team configuration does not exist", ErrorCode::TEAM_CONFIG_NOT_EXIST);
        }
        //转换用户ID
        $data = [
            'project_id' => $projectId,
            'user_id' => $this->getSaasUserID($userId),
        ];
        //团队配制信息
        $teamInfo = $teamInfo['list'][0];
        //增加成员
        return $this->saveTeamProjectMember($teamInfo, $data, $teamInfo['role_id']);
    }

    /**
     * 转换成saas用户ID --通过IM用户ID，多个以,拼接
     * @param $userId
     * @return string
     */
    private function getSaasUserID($userId)
    {
        //判断--传参用户ID类型
        $userIds = explode(',', $userId);
        foreach ($userIds as $val) {
            if (!is_numeric($val)) {
                throw new LogicException("Member error", ErrorCode::TEAM_USER_ID_ERROR);
            }
        }
        $saasUserIds = model(UserModel::class)->where(['union_id' => ['IN', $userIds]])->field('id')->column('id');
        //判断用户ID
        if (count($userIds) !== count($saasUserIds)) {
            throw new LogicException("Member error", ErrorCode::TEAM_USER_ID_ERROR);
        }

        return implode(',', $saasUserIds);
    }


    /**
     * 项目团队增加增加成员角色、删除角色
     * @param int $projectId 项目ID
     * @param int $teamId 团队ID
     * @param int $userId 用户ID
     * @param int $roleId 角色ID
     * @param int $type 操作类型
     * @return false|float|int|mixed|string
     */
    public function teamSaveUserRole(int $projectId, int $teamId, int $userId, int $roleId, int $type)
    {
        //获取团队信息
        $teamInfo = $this->getTeamConfig($teamId);
        if (empty($teamInfo['list'])) {
            throw new LogicException("Team configuration does not exist", ErrorCode::TEAM_CONFIG_NOT_EXIST);
        }
        //转换用户ID
        $userId = $this->getSaasUserID($userId);
        //删除成员角色
        if ($type == 2) {
            $rt = model(ProjectMemberModel::class)
                ->where(['project_id' => $projectId, 'team_id' => $teamId, 'user_id' => $userId, 'role_id' => $roleId])
                ->delete();
        } else {
            //增加---项目团队成员
            $rt = $this->addProjectTeamMember($teamInfo['list'][0], $projectId, $userId, $roleId);
        }
        return $rt;
    }

    /**
     * 增加---项目团队成员
     * @param array $teamInfo 团队信息
     * @param int $projectId 项目ID
     * @param int $userId 用户ID
     * @param int $roleId 角色ID
     * @return array|bool
     */
    private function addProjectTeamMember(array $teamInfo, int $projectId, int $userId, int $roleId)
    {
        //判断角色ID是否正确
        $requestData = ['param' => ['filter' => ['id' => $roleId], 'fields' => 'id,code']];
        $roleInfo = teamones_request('teamones-im', 'role/find', $requestData)['data'];
        if (empty($roleInfo)) {
            throw new LogicException("The role does not exist", ErrorCode::TEAM_ROLE_ERROR);
        }
        //成员类型
        $type = ($teamInfo['type'] == 1) ? ProjectMemberModel::PRODUCTION_TYPE : ProjectMemberModel::MANAGE_TYPE;

        //新增
        $addData = [];
        $addData['user_id'] = $userId;
        $addData['project_id'] = $projectId;
        $addData['team_id'] = $teamInfo['id'];
        $addData['role_id'] = $roleId;
        //判断记录是否已存在
        $hasOne = model(ProjectMemberModel::class)->where($addData)->field('id')->find();
        if ($hasOne) {
            throw new LogicException("The role has been added", ErrorCode::TEAM_ROLE_ERROR);
        }

        $addData['role_code'] = $roleInfo['code'] ?? '';
        $addData['type'] = $type;
        $addData['created'] = time();

        return model(ProjectMemberModel::class)->addItem($addData);
    }


    /**
     * 团队--删除成员
     * @param int $projectId 项目ID
     * @param int $teamId 团队ID
     * @param string $userId 用户ID
     * @return bool|float|int|string
     */
    public function teamDelUser(int $projectId, int $teamId, string $userId)
    {
        //转换用户ID
        $userId = $this->getSaasUserID($userId);
        //获取团队信息
        $rt = model(ProjectMemberModel::class)
            ->where([
                'project_id' => $projectId,
                'team_id' => $teamId,
                'user_id' => ['in', explode(',', $userId)]
            ])
            ->save(['is_delete' => 1]);

        return $rt;
    }

    /**
     * 保存团队成员
     * @param array $teamInfo 团队信息
     * @param array $param 增加的用户信息
     * @param string $roleIdStr 角色IDs
     * @return int
     */
    private function saveTeamProjectMember(array $teamInfo, array $param, string $roleIdStr)
    {
        $roleIdList = explode(',', $roleIdStr);
        if (empty($roleIdList)) {
            return 0;
        }
        //类型
        $type = ($teamInfo['type'] == 1) ? ProjectMemberModel::PRODUCTION_TYPE : ProjectMemberModel::MANAGE_TYPE;
        //角色信息--列表
        $roleList = teamones_request('teamones-im', 'role/select', [
            'param' => [
                'filter' => [
                    'role.id' => ['-in', $roleIdList]
                ]
            ]
        ])['data']['rows'];
        if (empty($roleList)) {
            throw new LogicException("The role does not exist", ErrorCode::TEAM_ROLE_ERROR);
        }
        $roleIdList = array_column($roleList, 'id');
        $roleList = array_column($roleList, null, 'id');
        //用户ID---支持批量修改
        $userList = explode(',', $param['user_id']);
        //保存用项目成员
        $projectMemberModel = model(ProjectMemberModel::class);

        $projectMemberModel->startTrans();
        try {
            //一个用户多个角色==多条记录
            foreach ($userList as $userId) {
                $modifyData = [
                    'user_id' => $userId,
                    'project_id' => $param['project_id'],
                    'team_id' => $teamInfo['id'],
                ];
                //先删除----已有角色记录
                $projectMemberModel->where($modifyData)->delete();

                foreach ($roleIdList as $val) {
                    //再新增
                    $modifyData['role_code'] = $roleList[$val]['code'] ?? '';
                    $modifyData['is_delete'] = 0;
                    $modifyData['role_id'] = $val;
                    $modifyData['type'] = $type;
                    $modifyData['created'] = time();
                    $projectMemberModel->addItem($modifyData);
                }
            }
            $projectMemberModel->commit();
        } catch (\Exception $e) {
            $projectMemberModel->rollback();
            trace('保存团队成员失败' . PHP_EOL . format_exception_info($e), 'ERR');
        }
        return 1;
    }


    /**
     * 项目团队成员列表
     * @param int $projectId 项目ID
     * @param int $teamId 团队ID
     * @param array $page 分页参数
     * @param array $roleCodes 角色code
     * @return array
     */
    public function getTeamUserList(int $projectId, int $teamId, array $page, array $roleCodes = [])
    {
        //查询条件
        $condition = [];
        $condition['is_delete'] = 0;
        $condition['project_id'] = $projectId;
        //团队查询--成员
        if ($teamId) {
            $condition['team_id'] = $teamId;
        }
        if (!empty($roleCodes)) {
            $condition['role_code'] = ['in', $roleCodes];
        }
        //获取团队信息--一个用户的角色ID不会多--group_concat
        $list = model(ProjectMemberModel::class)
            ->where($condition)
            ->field('group_concat(role_id) as role_id,user_id')
            ->group('user_id')
            ->order('created desc')
            ->page(...$page)
            ->select();

        if (empty($list)) {
            return [];
        }

        //整理数据--角色
        $roleList = teamones_request('teamones-im', 'role/select', [])['data']['rows'];
        $roleList = array_column($roleList, null, 'id');
        //用户信息
        $userIds = array_column($list, 'user_id');
        $userList = model(UserModel::class)->where(['id' => ['IN', $userIds]])->field('id,name,email,phone,avatar,union_id')->select();
        $userList = array_column($userList, null, 'id');

        foreach ($list as &$val) {
            $val['role_list'] = $this->clearRoleList($val['role_id'], $roleList);
            $val['user_info'] = $userList[$val['user_id']] ?? [];
        }

        return ['rows' => $list];
    }

    /**
     * 获取项目成员列表
     * @param int $projectId 项目ID
     * @param int $stepCategoryId 环节ID
     * @param int $isDelete 是否删除
     * @return array
     */
    public function getProjectUserList(int $projectId, int $stepCategoryId, int $isDelete = 0)
    {
        //通过环节ID，项目ID--获取团队信息
        $teamInfo = $this->getTeamConfig(0, $stepCategoryId);
        $teamList = $this->filterTeamConfigList($teamInfo['list'], $projectId);
        if (empty($teamInfo)) {
            return [];
        }

        $teamIdList = array_column($teamList, null, 'id');
        //查询条件
        $condition = [];
        $condition['project_id'] = $projectId;
        $condition['is_delete'] = $isDelete;
        if ($stepCategoryId) {
            $teamIds = array_column($teamList, 'id');
            if (empty($teamIds)) {
                return [];
            }
            $condition['team_id'] = ['in', $teamIds];
        } else {
            $condition['team_id'] = ['gt', 0];
        }

        //获取团队成员
        $list = model(ProjectMemberModel::class)
            ->where($condition)
            ->field('user_id,team_id')
            ->select();
        //分组group
        $userIds = array_unique(array_column($list, 'user_id'));
        $list = arrayGroup($list, 'team_id', 'user_id');

        if (empty($list)) {
            return [];
        }

        //用户信息
        $userList = model(UserModel::class)->where(['id' => ['IN', $userIds]])->field('id,name,union_id')->select();
        $userList = array_column($userList, null, 'id');

        foreach ($list as &$val) {
            $val['team_name'] = $teamIdList[$val['team_id']]['name'] ?? '';
            $val['step_category_id'] = $teamIdList[$val['team_id']]['step_category_id'] ?? [];
            $val['children'] = $this->clearUserList($val['user_id'], $userList);
        }

        return ['rows' => $list];
    }


    /**
     * 整理用户信息信息
     * @param string $userIds 用户ID
     * @param array $userList 用户列表
     * @return array
     */
    private function clearUserList(string $userIds, array $userList)
    {
        //角色--信息
        $userIdList = explode(',', $userIds);
        $result = [];
        foreach ($userIdList as $val) {
            if (isset($userList[$val])) {
                $result[] = $userList[$val];
            }
        }
        return $result;
    }

    /**
     * 排期---环节组装
     * @param string $StepCategoryIds
     * @return array
     */
    public function clearPlanStepCategory(string $StepCategoryIds = '')
    {
        //获取团队环节配制--环节
        $teamInfo = $this->getTeamConfig();
        //组装--环节详情
        $producerStepCategoryList = TemplateService::getInstance()->findStepCategoryShowList();
        if (empty($producerStepCategoryList)) {
            return [];
        }
        $producerStepCategoryList = array_column($producerStepCategoryList, null, 'id');
        //过滤显示环节
        $filterStepCategoryIds = [];
        if (!empty($StepCategoryIds)) {
            $filterStepCategoryIds = explode(",", $StepCategoryIds);
        }
        // 筛选出显示的环节id
        $group = [];
        $showStepCategoryIdProjectIds = $showStepCategoryIdProjectList = $teamStepCategoryNameMap = [];
        foreach ($teamInfo['list'] as $teamVal) {
            foreach ($teamVal['step_category_id'] as $val) {
                if (!empty($filterStepCategoryIds) && !in_array($val, $filterStepCategoryIds)) {
                    continue;
                }
                //环节详情
                $stepCategory = $producerStepCategoryList[$val] ?? [];
                //组装返回数组
                $showStepCategoryIdProjectIds[] = $val;
                $showStepCategoryIdProjectList[$val] = $stepCategory;
                //环节ID  -- 对映团队环节名称
                $teamStepCategoryNameMap[$val] = $teamVal['step_category_name'];
                $group[$teamVal['step_category_name']]['children'][] = $stepCategory;
                $group[$teamVal['step_category_name']]['children_ids'][] = $val;
                $group[$teamVal['step_category_name']]['module_code'] = $stepCategory['module_code'] ?? '';
                $group[$teamVal['step_category_name']]['id'] = $teamVal['id'];
                $group[$teamVal['step_category_name']]['name'] = $teamVal['step_category_name'];
                $group[$teamVal['step_category_name']]['link_module_code'] = 'show_step_category';
                $group[$teamVal['step_category_name']]['plan_show'] = $teamVal['plan_show'] ?? 1;

                //属性列表
                $i = 0;
                $list = [];
                if ($teamVal['attribute']) {
                    foreach ($teamVal['attribute'] as $attr) {
                        $list[$i]['attribute'] = $attr;
                        $list[$i]['attribute_plan'] = [];
                        $i++;
                    }
                }
                $list[$i]['attribute'] = $teamVal['step_category_name'];
                $list[$i]['attribute_plan'] = [];

                $group[$teamVal['step_category_name']]['attribute_list'] = $list;
            }
        }
        return [$showStepCategoryIdProjectIds, $showStepCategoryIdProjectList, $group, $teamStepCategoryNameMap];
    }

    /**
     * 获取团队环节--对映--环节ID
     * @return array
     */
    public function getTeamStepCategoryMap()
    {
        //获取团队环节配制--环节
        $teamInfo = $this->getTeamConfig();
        $map = [];
        foreach ($teamInfo['list'] as $teamVal) {
            foreach ($teamVal['step_category_id'] as $val) {
                $map[$val] = $teamVal['id'];
            }
        }
        return $map;
    }

    /**
     * 获取用户所在团队信息列表
     * @param int $projectId 项目ID
     * @param int $userId 用户ID
     * @return array
     */
    public function getUserTeamList(int $projectId, int $userId)
    {
        //查询条件
        $condition = [];
        $condition['project_id'] = $projectId;
        $condition['user_id'] = $userId;
        $condition['is_delete'] = 0;
        $condition['team_id'] = ['gt', 0];

        $userList = model(ProjectMemberModel::class)
            ->field('team_id,role_id,role_code')
            ->where($condition)
            ->select();
        if (empty($userList)) {
            return [];
        }

        //补充--团队信息
        $teamInfo = ProjectTeamService::getInstance()->getTeamConfig();
        $teamList = array_column($teamInfo['list'], null, 'id');

        foreach ($userList as &$val) {
            $val['name'] = $teamList[$val['team_id']]['name'] ?? '';
            $val['step_category_ids'] = $teamList[$val['team_id']]['step_category_id'] ?? [];
        }

        return [
            'project_id' => $projectId,
            'user_id' => $userId,
            'team_list' => $userList
        ];
    }


    /**
     * 整理角色信息
     * @param string $teamIds 团队IDs
     * @param array $teamList 团队信息列表
     * @return array
     */
    private function clearTeamList(string $teamIds, array $teamList)
    {

        $teamList = array_column($teamList, null, 'id');
        //角色--信息
        $teamIdList = explode(',', $teamIds);
        $result = [];
        foreach ($teamIdList as $val) {
            if (isset($teamList[$val]) && $val) {
                $result[] = $teamList[$val];
            }
        }
        return $result;
    }

    /**
     * 通过角色id和环节列表,匹配团队id
     * @param int $roleId
     * @param array $stepCategoryIdList
     * @return int
     */
    public function matchStepCategoryNameTeamData(int $roleId, array $stepCategoryIdList): int
    {
        $teamId = 0;
        if (empty($stepCategoryIdList) || empty($roleId)) {
            return $teamId;
        }
        $projectTeamConfig = OptionsService::getInstance()->getOptionsData('project_team_config');
        if (empty($projectTeamConfig)) {
            return $teamId;
        }
        foreach ($projectTeamConfig as $projectTeamConfigItem) {
            $configRoleIdIds = $projectTeamConfigItem['role_id'] . ',' . $projectTeamConfigItem['extra_role_id']; // 默认角色
            $configRoleIdList = explode(',', $configRoleIdIds);
            $configStepCategoryIdList = $projectTeamConfigItem['step_category_id'] ?? [];
            $configStepCategoryDiff = array_intersect($stepCategoryIdList, $configStepCategoryIdList);
            if (in_array($roleId, $configRoleIdList) && $configStepCategoryDiff) {
                $teamId = $projectTeamConfigItem['id'];
            }
        }
        return $teamId;
    }

}
